//获得所有弹幕
const axios = require('axios');
const playListMsg = require('./playListMsg');
const basepb = require('./v1');

async function getCidDM(item){
  let playListDM = [];
  let cid = item.cid;
  let duration = item.duration;
  let n = duration % 360 == 0 ? parseInt(duration / 360) : parseInt(duration / 360 + 1);
  for (let i = 0; i < n; i++) {
    try {
      let data = await axios.get('http://api.bilibili.com/x/v2/dm/web/seg.so', {
        params: {
          type: 1,
          oid: cid,
          segment_index: i + 1
        },
        responseType: 'arraybuffer',
      })
      let U8A = new Uint8Array(data.data);
      let result = basepb.DmSegMobileReply.deserializeBinary(U8A);
      playListDM = playListDM.concat(result.array[0]);
    } catch (error) {
      console.log(error.response.status);
    }
  }
  return playListDM;
}

async function getDanmuku(bvId) {
  let danmuTotal = [];
  let msg = await playListMsg(bvId);
  for (let i = 0; i < msg.length; i++) {
    const item = msg[i];
    let listDM = await getCidDM(item);
    danmuTotal.push(listDM)
  }
  return danmuTotal;
}

module.exports = {getDanmuku,getCidDM};